﻿using System;
using System.Collections.Generic;
using System.Text;
using Framework.Platform.Components.UI.View;
using System.Reflection;

namespace Framework.Platform.Components.UI.Presenter
{
    public abstract class BaseNavigatorPresenter : BasePresenter<BaseNavigator>
    {
        private INavigatorDataLoader _NavigatorDataLoader;

        public INavigatorDataLoader NavigatorDataLoader
        {
            get { return _NavigatorDataLoader; }
            set
            {
                if (_NavigatorDataLoader != value)
                {
                    _NavigatorDataLoader = value;
                    _NavigatorDataLoader.DataLoaded += new EventHandler<NavigatorDataLoadedEventArgs>(DataLoader_DataLoaded);
                }
            }
        }

        public BaseNavigatorPresenter(BaseNavigator view)
            : base(view)
        {
        }

        protected virtual void DataLoader_DataLoaded(object sender, NavigatorDataLoadedEventArgs e)
        {
            NavigatorItemBase parent = this.View.GetItemByKey(e.ParentKey);
            if (parent != null)
            {
                parent.HasLoadChildren = true;
            }
            foreach (NavigatorItemBase item in e.Datas)
            {
                this.View.AddItem(item);
            }
        }

        protected virtual void View_SelectedChanged(object sender, ViewEventArgs e)
        {
            NavigatorSelectedChangedEventArgs arg = (NavigatorSelectedChangedEventArgs)e;
            if (arg.NewItem.IsLeaf && !arg.NewItem.HasLoadChildren)
            {
                this.NavigatorDataLoader.LoadData(arg.NewItem.Key);
            }
        }

        protected virtual void View_ViewLoad(object sender, EventArgs e)
        {
            if (this.NavigatorDataLoader != null)
            {
                this.NavigatorDataLoader.LoadData(null);
            }
        }
    }
}